/*
 * @LastEditors: 七七
 * @Date: 2023-01-06 10:24:46
 */
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
// import axios from 'axios';

export default class Search extends Component {

  //发布消息
  search = async () => {
    //获取用户输入(连续解构赋值:{keyWordElement:{value}}+重命名{value:keyWord})
    const { keyWordElement: { value: keyWord } } = this
    //发送请求前通知List更新状态
    PubSub.publish('atguigu', { isFirst: false, isLoding: true })

    /* //发送网络请求--使用axios发送
    axios.get(`/api1/search/users?q=${keyWord}`).then(
      response => {
        PubSub.publish('atguigu', { isLoding: false, users: response.data.items })
      },
      error => {
        PubSub.publish('atguigu', { isLoding: false, err: error.message })
      }
    ) */

    //发送请求--使用fetch发送（未优化）
    /*     fetch(`/api1/search/users?q=${keyWord}`).then(
          // response联系服务器
          // response.json()获取数据实例pending->数据实例是否获取成功
          response => {
            // console.log('联系服务器成功了', response.json());
            console.log('联系服务器成功了');
            return response.json()
          },
          // 断网联系服务器失败
          error => {
            console.log('联系服务器失败了', error);
            return new Promise(() => { })
          }
        ).then(
          response => {
            console.log('获取数据成功', response.items);
          },
    
          error => {
            console.log('获取数据失败', error);
          }
        ) */

    //发送请求--使用fetch发送（优化）
    try {
      // await 只接收成功的结果
      // 获取成功的response
      const response = await fetch(`/api1/search/users?q=${keyWord}`);
      // 获取成功的data数据 
      // response.json() => promise实例
      const data = await response.json();
      PubSub.publish('atguigu', { isLoding: false, users: data.items });
    } catch (error) {
      PubSub.publish('atguigu', { isLoding: false, err: error.message });
    }
  }

  render() {
    return (
      <div>
        <section className="jumbotron">
          <h3 className="jumbotron-heading">搜索Github用户</h3>
          <div>
            <input ref={c => this.keyWordElement = c} type="text" placeholder="点击关键词搜索" />&nbsp;
            <button onClick={this.search}>搜索</button>
          </div>
        </section>
      </div>
    )
  }
}
